package com.iiapk.gridnew.view;

import java.util.List;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;

import com.iiapk.gridnew.domain.Article;

public class NewsPanel1 extends NewsPanel{
	
	private int random;
	private boolean flag=false;
	
	/**
	 * @param context
	 * @param dataSource
	 */
	public NewsPanel1(Context context,List<Article> dataSource,int i) {
		super(context,dataSource);
	}
	
	public NewsPanel1(Context context,List<Article> dataSource) {
		super(context,dataSource);
	}
	
	public void refreshDataSource(){
		mOrientation = HORIZONTAL;
		flag=true;
	}
	
	private void refreshRandom(){
		int random1 = (int)(Math.random()*100);
   		int random2 = -(int)(Math.random()*100);
   		random = Math.abs(random1)>Math.abs(random2)?random2:random1;
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		if(!flag)
			return;
		int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
      	int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
		final int count = getChildCount();
		int perHeight = parentHeight/(int)Math.ceil(count/2.0);
		int perWidth = parentWidth;
		
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(perWidth, perHeight);
		LinearLayout.LayoutParams lpHalf1 = new LinearLayout.LayoutParams(perWidth/2, perHeight);
		LinearLayout.LayoutParams lpHalf2 = new LinearLayout.LayoutParams(perWidth/2, perHeight);
		
		int randomSum = (int) (Math.random()*count);
		if(randomSum%2==1)
			randomSum-=1;
		
		for(int i=0,j=0;i<count;i++){
			if(i==randomSum){
				View child0 = getChildAt(randomSum);
				if(child0!=null){
					child0.setLayoutParams(lp);
					measureChildWithMargins(child0, widthMeasureSpec, 0, heightMeasureSpec, 0);
				}
				continue;
			}
			if(j==0){
				refreshRandom();
	       		lpHalf1 = new LinearLayout.LayoutParams(perWidth/2+random, perHeight);
	       		lpHalf2 = new LinearLayout.LayoutParams(perWidth/2-random, perHeight);
	       		View child = getChildAt(i);
	       		child.setLayoutParams(lpHalf2);
	       		measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
	       		j=1;
			}else{
				j=0;
				View child = getChildAt(i);
	       		child.setLayoutParams(lpHalf1);
	       		measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
			}
       	}
		setMeasuredDimension(parentWidth, parentHeight);
	}
	
}
